<script setup lang="ts">
import { dayjs } from 'element-plus'
import { useLoadData, type ListItem } from './composable'

import ReportComponent from './components/ReportComponent.vue'
import ReportRecordsModal from './components/ReportRecordsModal.vue'
import { REPORT_AUDIT_STATUS, REPORT_ACTION } from '@/enum'
import { auditReportAll, getReportName as _getReportName } from '@/api/modules/dataReport'

const modalRef = ref<InstanceType<typeof ReportRecordsModal>>()
const status = ref<REPORT_AUDIT_STATUS>()
const month = ref(dayjs().subtract(1, 'month').format('YYYY-MM'))
const reportName = ref('')
const reportList = ref<string[]>([])
const visible = ref(false)
const socialCreditCode = ref('')

const {
  loading,
  tableData,
  statusOptions,
  pagination,
  enterpriseList,
  queryList,
  getStatusText,
  showAction,
  exportFile,
  audit,
  getTagColor,
  exportReportStatusAll,
} = useLoadData()

const currentRow = ref<ListItem>()
const title = computed(() => {
  return `${unref(currentRow.value?.enterprise) ?? ''} - ${unref(currentRow)?.name ?? ''}`
})
const showPassButton = computed(() => {
  // 当前报表是”未填写“ => 不显示按钮
  // 当前报表是”已填写“ => 不显示按钮
  // 当前报表是”已上报“ => 显示”通过“和”退回“按钮
  // 当前报表是”已审核“ => 只显示”退回“按钮
  // 当前报表是”退回“   => 不显示按钮
  return currentRow.value ? currentRow.value.status === REPORT_AUDIT_STATUS.REPORTED : false
})
const showBackButton = computed(() => {
  // 当前报表是”未填写“ => 不显示按钮
  // 当前报表是”已填写“ => 不显示按钮
  // 当前报表是”已上报“ => 显示”通过“和”退回“按钮
  // 当前报表是”已审核“ => 只显示”退回“按钮
  // 当前报表是”退回“   => 不显示按钮
  return currentRow.value ? [REPORT_AUDIT_STATUS.REPORTED, REPORT_AUDIT_STATUS.RESOLVED].includes(currentRow.value.status) : false
})

const filterReportList = computed(() => {
  const r = unref(reportName)
  if (r === '' || r === undefined || r === null)
    return reportList.value
  return reportList.value.filter((item) => {
    return item.includes(unref(reportName))
  })
})

const currentAction = ref<REPORT_ACTION>()
const isViewAction = computed(() => {
  return currentAction.value === REPORT_ACTION.DO_VIEW
})

async function getReportName() {
  const res = await _getReportName()
  reportList.value = res.data
}

function filterMethod(text: string) {
  if (!text)
    return
  reportName.value = (text ?? '').trim()
}

async function clickSearch() {
  if (!unref(month)) {
    ElMessage.warning('请选择报告期')
    return
  }
  pagination.pageNumber = 1
  await nextTick()
  queryList({
    month: unref(month),
    status: unref(status),
    socialCreditCode: unref(socialCreditCode),
    reportName: unref(reportName),
  })
}

function getTableData() {
  queryList({
    month: unref(month),
    status: unref(status),
    socialCreditCode: unref(socialCreditCode),
    reportName: unref(reportName),
  })
}

async function doAction(row: ListItem, action: REPORT_ACTION) {
  currentRow.value = row
  currentAction.value = action
  await nextTick()
  // 查看/审核
  if (action === REPORT_ACTION.DO_VIEW || action === REPORT_ACTION.DO_RESOLVE) {
    visible.value = true
  }
  // 历史操作
  if (action === REPORT_ACTION.DO_LOG) {
    modalRef.value?.open()
  }
  // 导出
  if (action === REPORT_ACTION.DO_EXPORT) {
    row.id && exportFile(row.id)
  }
}

async function clickPass() {
  const c = unref(currentRow)
  if (c && c.id) {
    await audit(c.id, 0)
    visible.value = false
    await nextTick()
    clickSearch()
  }
}

async function clickReject() {
  const c = unref(currentRow)
  if (c && c.id) {
    await audit(c.id, 1)
    visible.value = false
    await nextTick()
    clickSearch()
  }
}

async function clickExport() {
  const c = unref(currentRow)
  if (c && c.id) {
    exportFile(c.id)
  }
}

async function clickBack() {
  visible.value = false
  await nextTick()
  clickSearch()
}

async function clickQuickAudit() {
  const res = await ElMessageBox.confirm('是否一键审核已上报的报表？', '操作提示').catch(() => {})
  if (res === 'confirm') {
    await auditReportAll(unref(month))
    ElMessage.success('操作成功')
    clickSearch()
  }
}

function clickQuickExport() {
  exportReportStatusAll({
    month: unref(month),
    status: unref(status),
    socialCreditCode: unref(socialCreditCode),
    reportName: unref(reportName),
  })
}

onMounted(() => {
  getReportName()
  clickSearch()
})
</script>

<template>
  <div class="h-full w-full flex flex-col p-4">
    <div class="fs-14 flex items-center gap-3">
      <span>报告期：</span>
      <ElDatePicker v-model="month" :clearable="false" :editable="false" type="month" placeholder="请选择月份" value-format="YYYY-MM" format="YYYY-MM" />
      <span>企业名称：</span>
      <ElSelect v-model="socialCreditCode" class="!w-60" clearable>
        <ElOption v-for="item in enterpriseList" :key="item.socialCreditCode" :label="item.subsidiaryName" :value="item.socialCreditCode" />
      </ElSelect>
      <span>报表名称：</span>
      <ElSelect v-model="reportName" class="!w-60" clearable filterable :filter-method="filterMethod">
        <ElOption v-for="item in filterReportList" :key="item" :label="item" :value="item" />
      </ElSelect>
      <span>上报状态：</span>
      <ElSelect v-model="status" class="!w-60" clearable>
        <ElOption v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </ElSelect>
      <SearchButton @click="clickSearch" />
      <ElButton type="success" class="!-ml-1" @click="clickQuickAudit">
        一键审核
      </ElButton>
      <ElButton type="warning" class="!-ml-1" @click="clickQuickExport">
        一键导出
      </ElButton>
    </div>
    <ElTable
      v-loading="loading" :data="tableData"
      height="100%" class="alpha-block mt-4 !border-0"
      element-loading-custom-class="global-loading"
    >
      <template #empty>
        <TableEmpty />
      </template>
      <ElTableColumn label="企业名称" prop="enterprise" />
      <ElTableColumn label="报表名称" prop="name" />
      <ElTableColumn label="状态" prop="status">
        <template #default="scope">
          <span class="fs-12" :style="{ color: getTagColor(scope.row.status) }">
            {{ getStatusText(scope.row.status) }}
          </span>
        </template>
      </ElTableColumn>
      <ElTableColumn label="备注" prop="remark" />
      <ElTableColumn label="操作" :width="280">
        <template #default="scope">
          <ElButton
            v-if="showAction(scope.row.status, 1)"
            type="primary"
            size="small"
            @click="doAction(scope.row, REPORT_ACTION.DO_VIEW)"
          >
            查看
          </ElButton>
          <ElButton
            v-if="showAction(scope.row.status, 4)"
            type="warning"
            size="small"
            @click="doAction(scope.row, REPORT_ACTION.DO_RESOLVE)"
          >
            审核
          </ElButton>
          <ElButton
            v-if="showAction(scope.row.status, 2)"
            type="info"
            size="small"
            @click="doAction(scope.row, REPORT_ACTION.DO_LOG)"
          >
            历史操作
          </ElButton>
          <ElButton
            v-if="showAction(scope.row.status, 3)"
            type="success"
            size="small"
            @click="doAction(scope.row, REPORT_ACTION.DO_EXPORT)"
          >
            导出
          </ElButton>
        </template>
      </ElTableColumn>
    </ElTable>
    <ListsPagination
      v-model:page-num="pagination.pageNumber"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      @current-change="getTableData"
      @size-change="getTableData"
    />

    <FullscreenModal v-model="visible">
      <div v-if="visible" class="absolute inset-0 m-4 flex flex-col gap-4">
        <ElPageHeader class="flex-shrink-0 px-4 py-3" title="返回" content="报表数据" @back="clickBack" />
        <ReportComponent v-if="currentRow" :company="currentRow.enterprise" :social-credit-code="currentRow.socialCreditCode" :data-id="currentRow.id" :month="month" :title="title" :report-id="currentRow.tId">
          <template #action>
            <div class="absolute right-0 top-1/2 flex items-center -translate-y-1/1">
              <ElButton v-if="showPassButton && !isViewAction" type="success" @click="clickPass">
                通过
              </ElButton>
              <ElButton v-if="showBackButton && !isViewAction" type="danger" @click="clickReject">
                退回
              </ElButton>
              <ElButton type="primary" @click="clickExport">
                导出
              </ElButton>
            </div>
          </template>
        </ReportComponent>
      </div>
    </FullscreenModal>

    <ReportRecordsModal v-if="currentRow && currentRow.id" ref="modalRef" :data-id="currentRow.id" :title="`${currentRow.enterprise}-${currentRow.name}-操作记录`" />
  </div>
</template>
